package com.project.voicememoassistant.tools;

import com.project.voicememoassistant.model.Menstruation;
import com.project.voicememoassistant.model.Remind;
import com.project.voicememoassistant.model.User;
import com.project.voicememoassistant.service.FindService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.List;

//定时器
@Component
@Slf4j
public class Scheduler {
    @Resource
    private FindService findService;
    SimpleDateFormat dateFormatChina = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    public static String token = WechatSendTemplate.getAccessToken();
    //不能一次性写90分钟的循环
    @Scheduled(cron="0 30 1-23/3 * * ?")
    public void getToken1() {
        System.out.println("Start getting access_token ==>");
        token = WechatSendTemplate.getAccessToken();
        findService.updateToken(token);
        System.out.println("access_token ==> "+token);
    }
    @Scheduled(cron="0 0 0-23/3 * * ?")
    public void getToken2() {
        System.out.println("Start getting access_token ==>");
        token = WechatSendTemplate.getAccessToken();
        findService.updateToken(token);
        System.out.println("access_token ==> "+token);
    }
    //只能用这两个组合起来构成90分钟的循环

    @Scheduled(cron="0 * * * * ?") //每隔1 min执行一次
    //这里需要注意的是 使用 @Scheduled注解 方法后面是不可以跟参数的要不然会报错的，异常如下
    public void sendRemindTemplate(){
        System.out.println("Start checking remind === Current time is "+dateFormatChina.format(System.currentTimeMillis()));
        String url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token="+token;
        List<User> users = findService.findAllUser();
        if(users.size()!=0){
            for(User u:users){
                System.out.println("Start finding remind ==>");
                List<Remind> reminds = findService.findRemindByUidInSomeTimes(u.getUid());
                System.out.println("Finish finding remind ==> ResultNum = "+reminds.size());
                if(reminds.size()!=0){
                    for(Remind r:reminds){
                        WechatSendTemplate.sendTemplate(url,u.getUid(),r.getTime(),r.getContent(),findService.findATip());
                    }
                }
            }
        }
    }

    @Scheduled(cron="0 0 9 * * ?") //每隔1天执行一次9点
    public void sendMenstruationTemplate(){
        List<User> users = findService.findAllUser();
        String url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token="+token;
        if(users.size()!=0) {
            for (User u : users) {
                List<Menstruation> menstruation =  findService.findAllMenstruationByUidInSomeTimes(u.getUid());
                if(menstruation.size()!=0){
                    WechatSendTemplate.sendMenstruationTemplate(url,u.getUid());
                }
            }
        }
    }
}
